package com.zhanghe.study.thread.lock;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteDemo {
    public static void main(String[] args) {
        TheData theData = new TheData();
        for (int i = 0; i < 3; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    theData.get();
                }
            }).start();
        }

        for (int i = 0; i < 3; i++) {
            int temp = i;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    theData.put("第" + temp + "次修改");
                }
            }).start();
        }
    }
}


class TheData {
    private String data = "hello";
    ReadWriteLock lock = new ReentrantReadWriteLock();

    public void get() {
        lock.readLock().lock();  //开读锁  防止写进程进入
        try {
            System.out.println(Thread.currentThread().getName() + "读线程进来");
            Thread.sleep(200);
            System.out.println(Thread.currentThread().getName() + "读线程完成,data为" + data);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.readLock().unlock();  //读锁解开
        }
    }

    public void put(String data) {
        lock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "写线程开始");
            this.data = data;
            Thread.sleep(100);
            System.out.println(Thread.currentThread().getName() + "写线程完成，data为" + data);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.writeLock().unlock();
        }
    }
}
